package cn.hsa.fqz.task.controller;

import cn.hsa.fqz.common.enums.FileType;
import cn.hsa.fqz.common.enums.IncidentsResultEnum;
import cn.hsa.fqz.handler.base.BaseController;
import cn.hsa.fqz.task.entity.*;
import cn.hsa.fqz.task.enums.CheckResultEnums;
import cn.hsa.fqz.task.enums.UserCategoryEnums;
import cn.hsa.fqz.task.service.TSysFileAccessoryService;
import cn.hsa.fqz.task.service.TTaskMedcClueFeedbackService;
import cn.hsa.fqz.task.service.TTaskMedcClueService;
import cn.hsa.fqz.task.service.TTaskService;
import cn.hsa.fqz.task.service.dto.*;
import cn.hsa.fqz.util.UserRegionUtils;
import cn.hsa.hsaf.core.framework.context.HsafContextHolder;
import cn.hsa.hsaf.core.framework.util.CurrentUser;
import cn.hsa.hsaf.core.framework.util.PageResult;
import cn.hsa.hsaf.core.framework.web.WrapperResponse;
import cn.hsa.hsaf.core.fsstore.FSEntity;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author 丁志敏
 * @version v1.0
 * @apiNote 功能描述:()
 * @date create in 2022/9/21 17:15
 */
@Slf4j
@Api(value = "违规线索办理", tags = "违规线索办理")
@RestController
@RequestMapping("/medc/clue")
public class TClueMedController extends BaseController {

    @Autowired
    private TTaskMedcClueService taskMedcClueService;

    @Autowired
    private TTaskService tTaskService;

    @Autowired
    private TTaskMedcClueFeedbackService feedbackService;

    @Autowired
    private TSysFileAccessoryService sysFileAccessoryService;

    @Value("${zmjk.ck.host}")
    private String ckHost;

    @Value("${zmjk.ck.port}")
    private Integer ckPort;

    @Value("${zmjk.ck.passwd}")
    private String ckPasswd;

    @Value("${zmjk.template.path}")
    private String TEMPLATE_PATH;


    @ApiOperation(value = "根据任务查询医药机构违规线索", notes = "根据任务查询医药机构违规线索")
    @PostMapping("/list")
    public WrapperResponse<PageResult<TTaskMedcClueDO>> findListByTaskId(@RequestParam("taskId") Integer taskId,
                                                                   @RequestParam("pageNum") Integer pageNum,
                                                                   @RequestParam("pageSize") Integer pageSize
    ) {
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        LoginUserDTO loginUserDTO = super.getLoginUser(currentUser);
        return WrapperResponse.success(taskMedcClueService.findListByTaskId(pageNum,pageSize,taskId));
    }

    @ApiOperation(value = "申请办结", notes = "申请办结")
    @PostMapping("/apply/dealComplt")
    public WrapperResponse<Boolean> applyDealComplt(@RequestBody DealResultDTO dto) {
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        return WrapperResponse.success(taskMedcClueService.applyDealComplt(dto,currentUser));
    }

    @ApiOperation(value = "获取反馈统计信息", notes = "获取反馈统计信息")
    @GetMapping("/statistic/feedback")
    public WrapperResponse<List<TaskMedcClueFeedbackStatisticDTO>> statisticFeedback(@RequestParam("taskCode") String taskCode,@RequestParam(value = "region",required = false) String region){
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        LoginUserDTO loginUserDTO = getLoginUser(currentUser);
        List<TaskMedcClueFeedbackStatisticDTO> list = feedbackService.getFeedbackStatisticByRegion(ckHost,ckPort,ckPasswd,loginUserDTO,region,taskCode);
        return WrapperResponse.success(list);
    }


    @ApiOperation(value = "团伙数据导出", notes = "团伙数据导出")
    @GetMapping("/statistic/export")
    public void export(@RequestParam("taskCode") String taskCode,@RequestParam(value = "region",required = false) String region,
                       HttpServletResponse response) throws Exception{
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        LoginUserDTO loginUserDTO = getLoginUser(currentUser);
        List<TaskMedcClueFeedbackStatisticDTO> list = feedbackService.getFeedbackStatisticByRegion(ckHost,ckPort,ckPasswd,loginUserDTO,region,taskCode);
        if(CollectionUtils.isEmpty(list)){
            WrapperResponse resp = WrapperResponse.fail("当前任务:" + taskCode + " 还未产生分析结果");
            response.getOutputStream().write(JSON.toJSONString(resp).getBytes("GBK"));
            return;
        }
        String fileName = "行动编号("+taskCode+")线索反馈数据";
        //获取模板
        try {
            setHttpServletResponse(response,fileName);
            ServletOutputStream out = response.getOutputStream();
            String path = TEMPLATE_PATH+"clueFeedbackTemplate.xlsx";
            log.info("模板文件路径:" + path);
            File f = new File(path);
            ExcelWriter excelWriter = EasyExcel.write(out).withTemplate(f).build();

            WriteSheet sheet0 = EasyExcel.writerSheet(0).build();
            excelWriter.write(genStatisticXlsBO(list), sheet0);

            excelWriter.finish();
        } catch (Exception e) {
            log.error("导出失败={}", e.getMessage(),e);
        }
    }

    private List<MedcFeedbackStatisticXlsDTO> genStatisticXlsBO(List<TaskMedcClueFeedbackStatisticDTO> list) {
        List<MedcFeedbackStatisticXlsDTO> xlsDTOS = Lists.newArrayList();
        for (TaskMedcClueFeedbackStatisticDTO source:list) {
            MedcFeedbackStatisticXlsDTO target = new MedcFeedbackStatisticXlsDTO();
            BeanUtils.copyProperties(source,target);
            target.setFxdj(transFxdj(source.getFxdj()));
            xlsDTOS.add(target);
        }
        return xlsDTOS;
    }

    private String transFxdj(int fxdj){
        if(fxdj == 1){
            return "一般风险";
        }else if(fxdj == 2){
            return "中风险";
        }else if(fxdj == 3){
            return "高风险";
        }else{
            return "";
        }
    }

    private void setHttpServletResponse(HttpServletResponse response,String fileName) {
        response.setContentType("application/x-msdownload");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码
        try {
            fileName = URLEncoder.encode(fileName+".xlsx", "UTF-8").replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
    }

    @ApiOperation(value = "确认办结", notes = "确认办结")
    @GetMapping("/confirm/dealComplt")
    public WrapperResponse<Boolean> confirmDealComplt(@RequestParam("sequenceNo") String sequenceNo) {
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        return WrapperResponse.success(taskMedcClueService.confirmDealComplt(sequenceNo,currentUser));
    }

    @ApiOperation(value = "驳回申请", notes = "驳回申请")
    @PostMapping("/apply/reaudit")
    public WrapperResponse<Boolean> applyReaudit(@RequestBody ApplyReauditDTO dto) {
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        return WrapperResponse.success(taskMedcClueService.applyReaudit(dto,currentUser));
    }

    @ApiOperation(value = "医药线索添加反馈", notes = "医药线索添加反馈")
    @PostMapping("/addFeedback")
    public WrapperResponse<Boolean> addFeedback(@RequestBody AddMedcFeedbackDTO create) {

        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        String proviceCode = "";String cityCode = "";
        TTask tTask = tTaskService.findById(create.getTaskId());
        if(tTask.getResult().equals(IncidentsResultEnum.FINISHED.name())){
            return WrapperResponse.fail("当前任务已经办结，不能添加线索反馈内容",null);
        }
        UserCategoryEnums userCategoryEnums = UserRegionUtils.getUserCateEnumByAscm(currentUser.getAdmDvs());
        if(userCategoryEnums == UserCategoryEnums.CITY){
            cityCode = currentUser.getAdmDvs();
        }
        else{
            proviceCode = currentUser.getAdmDvs();
        }
        boolean isExsitCheckNone = feedbackService.isCheckNone(create,proviceCode,cityCode);
        if(create.getCheckResult().intValue() != CheckResultEnums.NONE.getValue().intValue() && isExsitCheckNone){
            return WrapperResponse.fail("当前线索已经查否，需要删除才能添加其他结果反馈信息！",null);
        }
        return WrapperResponse.success(feedbackService.add(currentUser,create));
    }
    @ApiOperation(value = "医药线索反馈删除", notes = "医药线索反馈删除")
    @DeleteMapping("/deleteFeedback")
    public WrapperResponse<Boolean> delFeedback(@RequestParam("feedbackId") Integer id) {
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        return feedbackService.delete(currentUser,id);
    }

    @ApiOperation(value = "医药线索反馈查询", notes = "医药线索反馈查询")
    @GetMapping("/feedback/list")
    public WrapperResponse<List<TTaskMedcClueFeedbackDO>> feedbackList(@RequestParam("fxdj")Integer fxdj,@RequestParam Integer taskId,@RequestParam String medcCode) {
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        return WrapperResponse.success(feedbackService.getLists(taskId,medcCode,fxdj));
    }


    @ApiOperation(value = "已反馈线索分页查询", notes = "已反馈线索分页查询")
    @PostMapping("/feedbacked/page/list")
    public WrapperResponse<PageResult<MedcFeedbackDetailsDTO>> feedbackedPageList(@RequestBody TaskFeedbackQueryDTO dto) {
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        LoginUserDTO loginUserDTO = getLoginUser(currentUser);
        return WrapperResponse.success(feedbackService.feedbackedPageList(loginUserDTO,dto));
    }

    @ApiOperation(value = "已反馈线索导出", notes = "已反馈线索导出")
    @PostMapping("/feedback/export")
    public void detailExport(@RequestBody TaskFeedbackQueryDTO dto,
                       HttpServletResponse response) throws Exception{
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        LoginUserDTO loginUserDTO = getLoginUser(currentUser);
        String taskCode = dto.getCondition().getTaskCode();
        List<MedcFeedbackDetailsDTO> list = feedbackService.feedbackedList(loginUserDTO,dto);
        if(CollectionUtils.isEmpty(list)){
            WrapperResponse resp = WrapperResponse.fail("当前任务:" + taskCode + " 没有反馈记录");
            response.getOutputStream().write(JSON.toJSONString(resp).getBytes("GBK"));
            return;
        }
        String fileName = "行动编号("+taskCode+")线索反馈详情";
        //获取模板
        try {
            setHttpServletResponse(response,fileName);
            ServletOutputStream out = response.getOutputStream();
            ExcelWriter write = EasyExcel.write(out,MedcFeedbackDetailXlsDTO.class).build();
            WriteSheet sheet0 = EasyExcel.writerSheet(0).build();
            write.write(genFeedbackDetailXlsBO(list), sheet0);
            write.finish();
            out.flush();
            out.close();
        } catch (Exception e) {
            log.error("导出失败={}", e.getMessage(),e);
        }
    }

    private List<MedcFeedbackDetailXlsDTO> genFeedbackDetailXlsBO(List<MedcFeedbackDetailsDTO> list) {
        List<MedcFeedbackDetailXlsDTO> result = Lists.newArrayList();
        for (MedcFeedbackDetailsDTO source: list) {
            MedcFeedbackDetailXlsDTO target = new MedcFeedbackDetailXlsDTO();
            BeanUtils.copyProperties(source,target);
            target.setFxdj(source.getFxdjDesc());
            target.setCheckResult(source.getCheckResultDesc());
            result.add(target);
        }
        return result;
    }

    @ApiOperation(value = "医药线索反馈详情", notes = "医药线索反馈详情")
    @GetMapping("/feedback/detail")
    public WrapperResponse<TTaskMedcClueFeedbackDO> feedbackDetail(@RequestParam Integer feedbackId) {
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        return WrapperResponse.success(feedbackService.detail(feedbackId));
    }


    @ApiOperation(value = "文件上传", notes = "文件上传")
    @PostMapping("/file/upload")
    public WrapperResponse<String> uploadFile(@RequestParam("taskCode") String taskCode,@RequestParam("medcCode") String medcCode,
                                                               @RequestParam MultipartFile file) {
        /*if(file.getSize()>20*1024*1024){
            return WrapperResponse.error(500, "超过文件大小上限", null);
        }*/
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        LoginUserDTO dto = super.getLoginUser(currentUser);
        try {
            String accessoryId =  DigestUtils.md5Hex(taskCode+medcCode);
            return WrapperResponse.success(sysFileAccessoryService.upload(accessoryId,FileType.MED,dto, file));
        } catch (Exception e) {
            e.printStackTrace();
            return WrapperResponse.error(500, "文件上传失败", e.getMessage());
        }
    }

/*    public static void main(String[] args) {
        String accessoryId =  DigestUtils.md5Hex("3343fdafdsaf4-44424332r23");
        System.out.println(accessoryId);
    }*/

    @ApiOperation(value = "文件列表", notes = "文件列表")
    @GetMapping("/file/list")
    public WrapperResponse<List<TSysFileDO>> listFiles(@RequestParam("taskCode") String taskCode,@RequestParam("medcCode") String medcCode){
        String accessoryId =  DigestUtils.md5Hex(taskCode+medcCode);
        List<TSysFileDO> result = sysFileAccessoryService.list(accessoryId,FileType.MED);
        return WrapperResponse.success(result);
    }

    @ApiOperation(value = "文件下载", notes = "文件下载")
    @GetMapping("/file/download")
    public void downloadFile(HttpServletResponse response,@RequestParam("fileNo")String fileNo,@RequestParam("feedbackId")Integer feedbackId) {
        try {
            TTaskMedcClueFeedbackAttachmentDO attachmentDO = feedbackService.getAttachmentByFeedbackAndFileNo(fileNo, feedbackId);
            response.setHeader("Content-Type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            String filenameEncoder = "";
            String fileName = attachmentDO.getFileName();
            filenameEncoder = URLEncoder.encode(fileName, "utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filenameEncoder);
            InputStream inputStream = null;
            FSEntity fsEntity = sysFileAccessoryService.get(null,FileType.MED,fileName);
            inputStream = fsEntity.getInputstream();
            OutputStream out = null;
            try {
                out = response.getOutputStream();
                IOUtils.copy(inputStream, out);
                out.flush();
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
